package com.zg.scf.config.support;

/**
 * DESCRIPTION
 *
 * @author zhanfeng.liang
 * @since 2025-08-01
 */

import com.zg.common.core.R;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.http.converter.HttpMessageConverter;

import java.io.IOException;
import java.lang.reflect.Type;

public class FeignResponseDecoder implements Decoder {

    private final Decoder defaultDecoder;
    private final ObjectMapper objectMapper;

    // 注入默认解码器和消息转换器
    public FeignResponseDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        this.defaultDecoder = new org.springframework.cloud.openfeign.support.SpringDecoder(messageConverters);
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        // 1. 先用默认解码器解析为 ApiResponse
        R<?> apiResponse = (R<?>) defaultDecoder.decode(response, R.class);

        // 2. 校验响应状态（可选）
        if (apiResponse.getCode() != 1) {
            throw new RuntimeException("接口调用失败: " + apiResponse.getMessage());
        }

        // 3. 只返回 data 字段
        return apiResponse.getData();
    }
}
